import { onMounted, unref, isRef, watch, onUnmounted } from 'vue'
import { echarts } from '@/plugins/echarts'

export function useEcharts(target, options) {
  let echartsInstance = null

  const init = () => {
    const unrefTarget = unref(target)
    if (!unrefTarget) {
      console.warn('init :', `The target is ${unrefTarget}`)
      return
    }
    echartsInstance = echarts.init(unrefTarget)
  }

  const update = options => {
    if (!echartsInstance) {
      console.warn('update :', 'The echarts instance is uninitialized')
      init()
    }
    echartsInstance?.setOption(unref(options))
  }

  const resize = () => {
    if (!echartsInstance) {
      console.warn('resize :', 'The echarts instance is uninitialized')
      init()
    }
    echartsInstance?.resize()
  }

  if (isRef(target)) {
    const stop = watch(target, el => {
      if (el) {
        init()
        update(unref(options))
        stop()
      }
    })
  } else {
    onMounted(init)
  }

  if (isRef(options)) {
    watch(options, newVal => update(unref(newVal)))
  }

  window.addEventListener('resize', resize)
  onUnmounted(() => {
    echartsInstance?.dispose()
    window.removeEventListener('resize', resize)
  })

  return {
    echarts: echartsInstance,
    update,
    resize
  }
}
